package net.wicp.tams.common.io;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

/***
 * 只读的方式打开文件，自由读
 * 
 * @author zhoujunhui
 *
 */
public class InputStreamRamdomRead extends InputStream {
	//
	private final RandomAccessFile file;
	protected final File oriFile;

	public InputStreamRamdomRead(File file) throws IOException {
		this.file = new RandomAccessFile(file, "r");
		this.oriFile = file;
	}

	/***
	 * 还有多少可字节可用
	 */
	@Override
	public int available() throws IOException {
		final long fp = this.file.getFilePointer();
		return (int) (this.file.length() - fp);
	}

	@Override
	public void close() throws IOException {
		this.file.close();
	}

	@Override
	public int read() throws IOException {
		return this.file.read();
	}

	@Override
	public int read(byte b[], int off, int len) throws IOException {
		return this.file.read(b, off, len);
	}

	@Override
	public boolean markSupported() {
		return true;
	}

	protected long markPos = -1l;

	@Override
	public synchronized void mark(int readlimit) {
		try {
			markPos = this.file.getFilePointer();
		} catch (IOException e) {
			markPos = -1;
		}
	}

	@Override
	public synchronized void reset() throws IOException {
		if (markPos >= 0) {
			this.file.seek(markPos);
		}
	}

	/**
	 * 得到当前位置
	 * 
	 * @return 当前位置
	 */
	public long getCurPos() {
		try {
			return this.file.getFilePointer();
		} catch (IOException e) {
			return -1;
		}
	}

	public void seek(long pos) throws IOException {
		file.seek(pos);
	}

	// //////////
	// ////////////////////////////////////////下面是一些扩展方法////////////////////////////////////////////////////////////////////////////

	public byte[] readBytes(int length) throws IOException {
		final byte[] r = new byte[length];
		this.read(r, 0, length);
		return r;
	}

	public byte readByte() throws IOException {
		return readBytes(1)[0];
	}

}
